package com.example.internet.client;

import com.example.internet.client.dto.PeopleInfoRequest;
import com.example.internet.client.dto.PeopleInfoResponse;
import com.example.internet.client.BytesUtils;
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class ContactsClient {
    private static final SocketAddress ADDRESS = new InetSocketAddress("localhost", 8888);

    public static void main(String[] args) throws IOException {
        // 创建客⼾端 DatagramSocket
        DatagramSocket socket = new DatagramSocket();
        // 构造 request 请求数据
        PeopleInfoRequest request = createRequest();
        // 序列化 request
        byte[] requestData = request.toByteArray();
        // 创建 request 数据报
        DatagramPacket requestPacket = new DatagramPacket(requestData,
                requestData.length, ADDRESS);
        // 发送 request 数据报
        socket.send(requestPacket);
        System.out.println("发送成功！");
        // 创建 response 数据报，⽤于接收服务端返回的响应
        byte[] udpResponse = new byte[1024];
        DatagramPacket responsePacket = new DatagramPacket(udpResponse,
                udpResponse.length);
        // 接收 response 数据报
        socket.receive(responsePacket);
        // 获取有效的 response
        int length = BytesUtils.getValidLength(udpResponse);
        byte[] reqsponseData = BytesUtils.subByte(udpResponse, 0, length);
        // 反序列化 response，打印结果
        PeopleInfoResponse response = PeopleInfoResponse.parseFrom(reqsponseData);
        System.out.printf("接收到服务端返回的响应：%s", response.toString());
    }

    private static PeopleInfoRequest createRequest() {
        System.out.println("------输⼊需要传输的联系⼈信息-----");
        Scanner scan = new Scanner(System.in);
        PeopleInfoRequest.Builder peopleBuilder = PeopleInfoRequest.newBuilder();
        System.out.print("请输⼊联系⼈姓名: ");
        String name = scan.nextLine();
        peopleBuilder.setName(name);
        System.out.print("请输⼊联系⼈年龄: ");
        int age = scan.nextInt();
        peopleBuilder.setAge(age);
        scan.nextLine();
        for (int i = 0; ; i++) {
            System.out.print("请输⼊联系⼈电话" + (i + 1) + "(只输⼊回⻋完成电话新增): ");
            String number = scan.nextLine();
            if (number.isEmpty()) {
                break;
            }
            PeopleInfoRequest.Phone.Builder phoneBuilder = PeopleInfoRequest.Phone.newBuilder();
            phoneBuilder.setNumber(number);
            peopleBuilder.addPhone(phoneBuilder);
        }
        for (int i = 0; ; i++) {
            System.out.print("请输⼊备注" + (i + 1) + "标题 (只输⼊回⻋完成备注新增): ");
            String remarkKey = scan.nextLine();
            if (remarkKey.isEmpty()) {
                break;
            }
            System.out.print("请输⼊备注" + (i + 1) + "内容: ");
            String remarkValue = scan.nextLine();
            peopleBuilder.putRemark(remarkKey, remarkValue);
        }
        System.out.println("------------输⼊结束-----------");
        return peopleBuilder.build();
    }
}